
package com.huaweicloud.haydn.delivercore.agent.utils;

import static com.huaweicloud.haydn.delivercore.agent.config.Constants.FILETYPE_ZIP;
import static com.huaweicloud.haydn.delivercore.agent.config.Constants.SYS_URL;

import com.alibaba.fastjson.JSONObject;
import com.huaweicloud.haydn.delivercore.agent.common.exception.BusinessErrorEnum;
import com.huaweicloud.haydn.delivercore.agent.common.exception.BusinessException;
import com.huaweicloud.haydn.delivercore.agent.config.ObsAgencyConfig;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectRequest;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 上传探源结果到指定桶的指定目录下，并返回临时访问凭证。
 *
 * @since 2023-03-25
 */
@Slf4j
@Component
public class OBSUtil {
    @Autowired
    private ObsAgencyConfig obsAgencyConfig;

    /**
     * 将数据探源结果上传至指定桶的指定目录下，并返回下载该对象所需的凭证和路径
     *
     * @return 下载对象所需的凭证和路径
     */
    public JSONObject upload(String taskUuid) throws IOException {
        if (!obsAgencyConfig.isvalid()) {
            throw new BusinessException(BusinessErrorEnum.BASE_OBS_CONFIG_MISSING);
        }

        File file = new File(System.getProperty(SYS_URL), "result." + FILETYPE_ZIP);

        String objectDir = sanitizeDirs(obsAgencyConfig.getDirs());
        String objectKey = objectDir + taskUuid;
        try (ObsClient obsClient =
            new ObsClient(obsAgencyConfig.getAk(), obsAgencyConfig.getSk(), obsAgencyConfig.getObsEndPoint())) {
            PutObjectRequest putRequest = new PutObjectRequest();
            putRequest.setBucketName(obsAgencyConfig.getBucketName());
            putRequest.setObjectKey(objectKey);
            putRequest.setFile(file);
            // 设置过期时间
            putRequest.setExpires(1);
            obsClient.putObject(putRequest);
        }

        JSONObject infoJson = new JSONObject();
        infoJson.put("obs_end_point", obsAgencyConfig.getObsEndPoint());
        infoJson.put("bucket_name", obsAgencyConfig.getBucketName());
        infoJson.put("object_dir", objectDir);
        infoJson.put("domain_name", obsAgencyConfig.getDomainName());
        infoJson.put("agency_name", obsAgencyConfig.getAgencyName());
        infoJson.put("task_uuid", taskUuid);

        return infoJson;
    }

    private String sanitizeDirs(String dirs) {
        return Arrays.stream(dirs.split("/")).filter(StringUtils::isNotBlank).collect(Collectors.joining("/")) + "/";
    }

}
